package us.mmapp;

import java.util.ArrayList;
import java.util.HashMap;

import us.mmapp.entities.ObjectEntity;
import us.mmapp.interfaces.OnApplicationDataChangeListener;
import us.mmapp.interfaces.PhotoDownloaderListener;
import us.mmapp.services.PhotoDownloader;
import us.mmapp.util.ApplicationData;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * Manage Media Activity.
 * 
 */
public class ManageMediaActivity extends Activity implements PhotoDownloaderListener, OnApplicationDataChangeListener
{
	private ArrayList<ObjectEntity> mObjects;
	private ListView mListView;
	private Context mContext;
	private HashMap<String, ImageView> mThumbs;
	private View[] mViews;
	private ProgressDialog mProgress;
	private ArrayList<ObjectEntity> fullList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.manage_media_layout);

	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		PhotoDownloader.attach(this);
		ApplicationData.attach(this);
		mContext = this;
		mObjects = new ArrayList<ObjectEntity> ();
		mThumbs = new HashMap<String, ImageView>();
		
		setUp();
	}
	
	@Override
	protected void onPause()
	{
		super.onPause();
		// Clean up
		if (mObjects != null)
		{
			mObjects.clear();
		}
		mObjects = null;
		
		PhotoDownloader.deattach(this);
		ApplicationData.deattach(this);
	}

	private synchronized void setUp()
	{
		fullList = ApplicationData.getObjects();
		mListView = (ListView) findViewById(R.id.manage_list);
		
		// If not available, retrieve it from database
		if (fullList == null || fullList.size() == 0)
		{
			// Create the progressDialog since getting from local DB will take awhile
			mProgress = new ProgressDialog(mContext);
			mProgress.setMessage("Updating..");
			mProgress.setIndeterminate(true);
			mProgress.setCancelable(false);
			// Show the progress while doing the work
			AsyncTask<String, String, ArrayList<ObjectEntity>> t = new AsyncTask<String, String, ArrayList<ObjectEntity>>()
			{

				@Override
				protected ArrayList<ObjectEntity> doInBackground(
						String... params) {
					return ObjectEntity.getAllObjects(mContext);
				}
				@Override
				protected void onPostExecute(ArrayList<ObjectEntity> result)
				{
					fullList = result;
					setUpPartTwo();
				}
			};
			mProgress.show();
			t.execute("");
		}
		else
			setUpPartTwo();
	}
	private synchronized void setUpPartTwo()
	{
		// Filter it out
		for (ObjectEntity oe : fullList)
		{
			if (oe.getUid() == ApplicationData.getUserId())
			{
				mObjects.add(oe);
			}
		}
		
		
		mViews = new View[mObjects.size()];
		if (mObjects.size() == 0)
		{
			TextView tv = (TextView) findViewById(R.id.manage_text);
			tv.setVisibility(View.VISIBLE);
			tv.setText(R.string.no_items);
			
			mListView.setVisibility(View.GONE);
		}
		else
		{
			
			// Hide the text
			TextView tv = (TextView) findViewById(R.id.manage_text);
			tv.setVisibility(View.GONE);
			
			mListView.setVisibility(View.VISIBLE);
			
			mListView.setAdapter(new ArrayAdapter<ObjectEntity>(this, R.layout.manage_item, mObjects)
			{
				@Override
				public View getView(int position, View convertView, ViewGroup parent)
				{
					   View myView = mViews[position];
					   final ObjectEntity obj = (ObjectEntity)getItem(position);

					   LayoutInflater inflater = getLayoutInflater();
					   myView = inflater.inflate(R.layout.manage_item, null);
					   // Keep the view
					   mViews[position] = myView;
					   mThumbs.put(obj.getUrl_thumb(), (ImageView) myView.findViewById(R.id.manage_item_image));
					   
					   // The Image
					   ImageView iv = (ImageView) myView.findViewById(R.id.manage_item_image);
					   if (obj.getType() == 0)
						   iv.setImageDrawable(getResources().getDrawable(R.drawable.photo_ballon));
					   if (obj.getType() == 1)
						   iv.setImageDrawable(getResources().getDrawable(R.drawable.video_ballon));
					   if (obj.getType() == 2)
						   iv.setImageDrawable(getResources().getDrawable(R.drawable.audio_ballon));

					   Bitmap photo = null;

					   if (obj.getLocalThumb() != null && obj.getLocalThumb() != "")
					   {
						   photo = BitmapFactory.decodeFile(obj.getLocalThumb());
					   }
					   else
					   {
						   photo = PhotoDownloader.getPhoto(obj.getUrl_thumb());
					   }
					   if (photo != null)
					   {
						   iv.setImageBitmap(photo);
					   }

					   // Title
					   TextView titleView = (TextView) (myView.findViewById(R.id.manage_item_title));
					   titleView.setText(obj.getTitle().subSequence(0, Math.min(20, obj.getTitle().length())));

					   // Date
					   TextView dateView = (TextView) (myView.findViewById(R.id.manage_item_date));
					   dateView.setText(us.mmapp.util.TextUtils.convertDate(obj.getDateCreated()));

					   // Description
					   TextView descView = (TextView) (myView.findViewById(R.id.manage_item_desc));
					   descView.setText(obj.getDescription().subSequence(0, Math.min(100, obj.getDescription().length())));

					   // View Button
					   Button viewButton = (Button) (myView.findViewById(R.id.manage_view_button));
					   viewButton.setOnClickListener(new OnClickListener()
					   {
						   @Override
						   public void onClick(View v)
						   {
							   Intent intent = new Intent();
							   intent.setClass(mContext, CommentActivity.class);
							   Bundle bundle = new Bundle();
							   bundle.putInt("keyword", (int)obj.getId());
							   intent.putExtras(bundle);
							   startActivity(intent);	
						   }
					   });

					   // Edit Button
					   Button editButton = (Button) (myView.findViewById(R.id.manage_view_edit));
					   editButton.setOnClickListener(new OnClickListener()
					   {
						   @Override
						   public void onClick(View v)
						   {
							   Intent intent = new Intent();
							   intent.setClass(mContext, InfoActivity.class);
							   Bundle bundle = new Bundle();
							   bundle.putInt("keyword", (int)obj.getId());
							   bundle.putBoolean("new", false);
							   intent.putExtras(bundle);
							   startActivity(intent);	
						   }
					   });

					   return (myView);
					}
			});
			
			if (mProgress != null)
				mProgress.dismiss();
		}
	}
	@Override
	public void available(String location, Bitmap photo)
	{
		if (photo != null)
		{
			ImageView iv = mThumbs.get(location);
			if (iv != null)
			{
				iv.setImageBitmap(photo);
				iv.postInvalidate();
			}
		}
	}

	@Override
	public void onApplicationDataChange()
	{
		// re-setup everything
		setUp();
	}
}
